package keter.combofs.init;

import com.google.common.base.Strings;
import keter.combofs.core.ComboFs;
import keter.combofs.core.impl.ComboFsImpl;
import keter.combofs.core.impl.ComboFsS3Impl;
import keter.combofs.path.PathMaker;
import keter.combofs.path.impl.PathMakerFSImpl;
import keter.combofs.persist.ComboFileDao;
import keter.combofs.persist.impl.ComboFileDaoJDBCImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 初始化配置
 */
@Configuration
public class ComboFSAutoConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(ComboFSAutoConfiguration.class);

    @Value("${combofs.s3.bucket}")
    protected String bucket;

    static protected boolean s3IsAvailable;
    static {
        // Is S3 Available?
        try {
            s3IsAvailable = null != Class.forName("com.amazonaws.services.s3.AmazonS3Client");
        } catch (Throwable t) {
            s3IsAvailable = false;
        }
    }

    @Bean
    @ConditionalOnMissingBean
    public ComboFs initCombo() {
        ComboFs template;
        // 包含S3配置和驱动
        if(s3IsAvailable && !Strings.isNullOrEmpty(bucket)){
            logger.info("启用S3文件系统...");
            template = new ComboFsS3Impl();
        }
        else {
            logger.info("使用操作系统文件系统（默认策略）...");
            template = new ComboFsImpl();
        }
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    public PathMaker initPathMaker() {
        return new PathMakerFSImpl();
    }

    @Bean
    @ConditionalOnMissingBean
    public ComboFileDao initDao() {
        return new ComboFileDaoJDBCImpl();
    }

}
